<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--分类数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="categoryName"
            placeholder="请输入分类名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="categoryOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--库表数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="指标名称" prop="fieldName">
            <el-input
              v-model="queryParams.fieldName"
              placeholder="请输入指标名称"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
            
          </el-form-item>
          <el-form-item label="阶段模型" prop="fieldName">
           <el-cascader
            :options="modelCategoryOptions"
            :props="{ checkStrictly: true, value:'catId', label:'catName',children:'children' }"
            clearable></el-cascader>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:user:add']"
            >指标注册</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['system:user:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:user:remove']"
            >标记删除</el-button>
          </el-col>
          
        </el-row>
        <!-- :span-method="arraySpanMethod"-->
        <el-table
      :data="listFields"      
      border
      style="width: 100%">
          <el-table-column
          prop="step"
          label="所属阶段"
          width="180">
        </el-table-column>
        <el-table-column
          prop="modelName"
          label="所属模型">
        </el-table-column>
        <el-table-column
          prop="quotaName"
          sortable
          label="指标名称"></el-table-column>
        <el-table-column
          prop="quantizationType"
          sortable
          label="量化类型"></el-table-column>
        <el-table-column
          prop="rangeSetting"
          sortable
          label="范围设置"></el-table-column>
        <el-table-column
          prop="tips"
          sortable
          label="提示语"></el-table-column> 
        <el-table-column         
          sortable
          label="提示颜色" width="100">
          <template slot-scope="scope">
            <el-tag  type="danger" effect="dark" size="medium">
              {{scope.row.color}}
            </el-tag>
          </template>
          </el-table-column> 
        <el-table-column
          prop="category"          
          label="所属分类"></el-table-column>
        <el-table-column
          prop="remark"          
          label="备注"></el-table-column>
        <el-table-column
            label="操作"
            align="center"
            width="180"
            class-name="small-padding fixed-width"
          >
          <template slot-scope="scope">
              <el-button
                v-if="scope.row.projectId !== 1"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:user:remove']"
              >标记删除</el-button> 
          </template>
        </el-table-column>        
        </el-table>
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="字段名称" prop="projectName">
              <el-input v-model="form.fieldName" placeholder="请输入字段名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字段" prop="projectName">
              <el-input v-model="form.field" placeholder="请输入字段" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="归属分类" prop="catId">
                 
              <el-select v-model="form.catId" placeholder="请选择归属分类(库表）"  clearable filterable>
                <el-option
                  v-for="item in categoryOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
              <!--treeselect v-model="form.catId" :options="categoryOptions" :disable-branch-nodes="true" :show-count="true" placeholder="请选择归属领域" /-->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目代码" prop="projectCode">
              <el-input v-model="form.projectCode" placeholder="请输入项目代码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年份" prop="setYear">
              <el-input v-model="form.setYear" placeholder="请输入年份" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.projectId == undefined" label="行政区划" prop="fieldName">
              <el-input v-model="form.fieldName" placeholder="请输入行政区划" />
            </el-form-item>
          </el-col>          
          <el-col :span="12">
            <el-form-item label="状态">              
              <el-select v-model="form.status" placeholder="请选择标记状态"  clearable filterable>
                <el-option
                  v-for="item in optionsStatus"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 字段导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的字段数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCategory, getCategory, addCategory, updateCategory, delCategory, exportCategory } from "@/api/quota/dbTable/category";

import { categoryTree,listFields } from "@/api/quota/earlyWaring/config";

import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "project",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 字段表格数据
      listFields: null,
      // 弹出层标题
      title: "",
      // 分类树选项
      categoryOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 分类名称
     categoryName: undefined,
     modelCategoryOptions:undefined,
   
      // 状态数据字典
      statusOptions: [],

      // 当前分类
      currentCategory:{},
      //上次合并对象
      parentSpanMethod:undefined,

      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 字段导入参数
      upload: {
        // 是否显示弹出层（字段导入）
        open: false,
        // 弹出层标题（字段导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的字段数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fieldName: undefined,
        status: undefined,
        catId: undefined
      },
      // 表单校验
      rules: {
        fieldName: [
          { required: true, message: "字段名称不能为空", trigger: "blur" }
        ],
        nickName: [
          { required: true, message: "字段昵称不能为空", trigger: "blur" }
        ],
       catId: [
          { required: true, message: "归属分类不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "字段密码不能为空", trigger: "blur" }
        ],
        email: [
          { required: true, message: "邮箱地址不能为空", trigger: "blur" },
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ]
      },

      //标记项目状态
      optionsStatus: [{
          value: 0,
          label: '正常'
        }, {
          value: 1,
          label: '标记删除'
        }],

      //数据填报类型    
      optionsInsertType:[
        {label:'数据填报',value:'0'},
        {label:'计算类型',value:'1'},
        {label:'人工计算',value:'2'},
        {label:'系统生成',value:'4'},
      ],

      //字段类型
      optionsFieldType:[
        {label:'字符串',value:'varchar'},
        {label:'日期（年）',value:'year'},
        {label:'日期（年月）',value:'int'},
        {label:'日期（年月日）',value:'datetime'},
        {label:'整型数字',value:'bigint'},
        {label:'数字（16,4)',value:'decimal'}
      ]
    };
  },
  watch: {
    // 根据名称筛选分类树
   categoryName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();

    this.getTreeselect();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
    
  },
  methods: {
    // //配置合并行
    // arraySpanMethod( row, column, rowIndex, columnIndex ){
    //   if(this.parentSpanMethod === null){
    //     return {
    //           rowspan: 0,
    //           colspan: 0
    //         };
    //   }
      
    //   if( this.parentSpanMethod.row.quotaName == row.quotaName ){
    //     if(this.parentSpanMethod.rowSpan == null){
    //         this.parentSpanMethod.rowSpan=0;
    //     }          
    //     this.parentSpanMethod.rowSpan++;
    //   return {
    //           rowspan: 0,
    //           colspan: 0
    //       };
    //   }

    //   this.parentSpanMethod.row = row;
    //   this.parentSpanMethod.column = column;
    //   this.parentSpanMethod.rowIndex = rowIndex;
   
    //   return [1,2,3];
    // },
    /** 查询字段列表 */
    getList() {
      this.loading = true;  
      // let r = listFields(this.queryParams).then(response => {        
      //   this.listFields = response.rows;
      //   this.loading = false;
      // });
     
       this.listFields = listFields().data;
       this.loading = false;
    },
    /** 查询分类下拉树结构 */
    getTreeselect() {

      listCategory({parentId: '0',type: 'zbfl'}).then(response => {        
        this.modelCategoryOptions = response.rows;      
      });
      this.categoryOptions = categoryTree().data;
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.currentCategory = data;
      if(data.tableName == null){
        //TODO: 没有表名的时，展示分类下所有的表名（卡片）列表。
        return;
      }
      
      this.queryParams.catId = data.catId;
      this.getList();
    },
    // 字段状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$confirm('确认要"' + text + '""' + row.fieldName + '"字段吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return changeUserStatus(row.projectId, row.status);
        }).then(() => {
          this.msgSuccess(text + "成功");
        }).catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        projectId: undefined,
        catId: undefined,
        fieldName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.projectId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTreeselect();

      // getUser().then(response => {
        this.open = true;
        this.title = "数据库表注册";
      //   this.form.password = this.initPassword;
      // });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      const projectId = row.projectId || this.ids;
      getUser(projectId).then(response => {
        this.form = response.data;
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
        this.form.postIds = response.postIds;
        this.form.roleIds = response.roleIds;
        this.open = true;
        this.title = "修改字段";
        this.form.password = "";
      });
    },
    
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.projectId != undefined) {
            updateUser(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addUser(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const projectIds = row.projectId || this.ids;
      this.$confirm('是否确认删除字段编号为"' + projectIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delUser(projectIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有字段数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportUser(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "字段导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }    
  }
};
</script>